package com.example.blog_system.config;

import com.example.blog_system.common.AppVariable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description: 实现登录拦截器 (对是否登录进行统一验证)
 */
// 随着项目启动 而注入
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * true->用户已登录 false->用户未登录
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession httpSession = request.getSession(false);  // 从请求中读取 cookie 去获取对应的session对象 不存在则为null
        //当用户未登录 则重定向到 登录页面
        if (httpSession == null || httpSession.getAttribute(AppVariable.USER_SESSION_KEY) == null) {
            response.sendRedirect("/blog_login.html");
            return false;
        }
        return true;
    }
}
